<template>
  <div class="filter-container">
    <el-form v-model="state.selectForm.order">
    <el-row>
      <el-col span="3">
        <el-form-item label="客户姓名">
          <el-input  placeholder="请输入客户姓名" v-model="state.selectForm.order.customer.name" style="width: 150px;" clearable />
        </el-form-item>
      </el-col>
      <el-col span="3">
        <el-form-item label="发货地">
          <el-input  placeholder="请输入发货地" v-model="state.selectForm.order.line.startAddress" style="width: 150px;" clearable />
        </el-form-item>
      </el-col>
      <el-col span="3">
        <el-form-item label="时间">
          <el-date-picker
              type="date"
              placeholder="选择时间"
              v-model="state.selectForm.order.createTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 200px;"
              clearable
          />
        </el-form-item>
      </el-col>
      <el-col span="3">
        <el-form-item label="状态">
       <el-select placeholder="选择状态" v-model="state.selectForm.order.orderStatus" style="width: 150px;">
         <el-option label="全部" value=""/>
         <el-option label="未入库" value="0" />
         <el-option label="入库未包装" value="1" />
         <el-option label="已包装" value="2" />
         <el-option label="已出库" value="3" />
         <el-option label="已到货" value="4" />
       </el-select>
        </el-form-item>
      </el-col>
      <el-col span="3">
        <el-button @click="load()" >查询</el-button>
        <el-button type="primary" class="butT" @click="handleCreate()">新建</el-button>
      </el-col>
    </el-row>

    </el-form>
  </div>

  <el-table :data="state.dataList"  style="width: 100%" >
    <el-table-column label="ID" align="center" prop="id"></el-table-column>
    <el-table-column label="客户姓名" align="center" prop="customer.name"></el-table-column>
    <el-table-column label="客户电话" align="center" prop="customer.phone" width="150"></el-table-column>
    <el-table-column label="线路起点" align="center" prop="line.startAddress" width="150"></el-table-column>
    <el-table-column label="线路终点" align="center" prop="line.endAddress" width="150"></el-table-column>
    <el-table-column label="订单金额" align="center" prop="amount"></el-table-column>
    <el-table-column label="订单状态" align="center" prop="orderStatus"></el-table-column>
    <el-table-column label="订单创建时间" align="center" prop="createTime" width="110"></el-table-column>
    <el-table-column label="送货时间" align="center" prop="sendTime" width="110"></el-table-column>
    <el-table-column label="操作" align="center" fixed="right" width="180" >
      <template v-slot="{row}">
<!--        <el-button link type="primary" size="small" @click="addGoods(row)">增加货物</el-button>-->
        <el-button link type="primary" size="small" @click="addGoods(row)">查看详情</el-button>
        <el-button link type="success" size="small" @click="sendOrder(row)">发货</el-button>
        <el-button link type="success" size="small" @click="endOrder(row)">到货</el-button>
        <el-button link type="primary" size="small" @click="handleEidt(row)">修改</el-button>
        <el-button link type="danger" size="small" @click="handleDelete(row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>



  <!--  新增订单弹窗-->
  <el-dialog
      v-model="state.dialogFormVisible"
      title="新增订单"
      width="50%"
  >
    <template #footer>
        <span class="dialog-footer">
          <div class="filter-container">
            <el-form v-model="state.addOrderForm">
    <el-row>
        <el-col span="3">
        <el-form-item label="选择客户">
         <select
             v-model="state.addOrderForm.customer"
             placeholder="请选择客户"
             style="width: 240px"
         >
         <option
             v-for="item in state.options.customers"
             :key="item.id"
             :value="item"
             :label="item.name"
         />
         </select>
          <el-button @click="openCustomer">添加客户</el-button>
        </el-form-item>

      </el-col>

        <el-col span="3">
        <el-form-item label="发货地">
          <el-select  placeholder="请选择发货地" v-model="state.addOrderForm.line.startAddress" >
            <el-option
                v-for="item in state.options.startAddress"
                :key="item"
                :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col span="3">
        <el-form-item label="收货地">
          <el-input  placeholder="请输入收货地址" v-model="state.addOrderForm.line.endAddress"  clearable />
        </el-form-item>
      </el-col>
    </el-row>
 </el-form>

  </div>

          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="handleAdd">
            确定
          </el-button>
        </span>
    </template>
  </el-dialog>
<!--  货物列表添加插槽-->
  <el-dialog
      v-model="state.dialogFormVisibleAddGoods"
      title="添加货物"
      width="80%">
      <AddGoods>
      </AddGoods>
  </el-dialog>

  <el-dialog
      v-model="state.dialogFormVisibleCustomer"
      title="新增客户"
      width="30%"
  >
    <!--  新增用户弹窗-->
    <template #footer>
        <span class="dialog-footer">
          <div class="filter-container">
                <el-form v-model="state.customerFormData">
    <el-row>
      <el-col span="3">
        <el-form-item label="客户姓名">
          <el-input  placeholder="请输入客户姓名" v-model="state.customerFormData.name" clearable />
        </el-form-item>
      </el-col>
      <el-col span="3">
        <el-form-item label="客户电话">
          <el-input  placeholder="请输入客户电话" v-model="state.customerFormData.phone"  clearable />
        </el-form-item>
      </el-col>
      <el-col span="3">
        <el-form-item label="客户性别">
          <el-select  placeholder="请选择客户性别"  v-model="state.customerFormData.sex">
            <el-option label="男性" value="1" />
            <el-option label="女性" value="2" />
          </el-select>
        </el-form-item>
        </el-col>
      <el-col span="3">
        <el-form-item label="客户类别">
          <el-select placeholder="请输入客户类别" v-model="state.customerFormData.type" >
            <el-option label="个体客户" value="个体客户"></el-option>
  <el-option label="企业客户" value="企业客户"></el-option>

          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
            </el-form>
  </div>

          <el-button @click="state.dialogFormVisibleCustomer = false">取消</el-button>
          <el-button type="primary" @click="addCustomer">
            确定
          </el-button>
        </span>
    </template>
  </el-dialog>

  <!--修改订单弹窗-->
  <el-dialog
      v-model="state.dialogFormVisible4Edit"
      title="修改订单"
      width="30%"
  >
    <template #footer>
        <span class="dialog-footer">
          <div class="filter-container">
            <el-form :model="state.formData">
    <el-row>
        <el-col span="3">
        <el-form-item  label="订单号">
          <el-input   v-model="state.formData.id" clearable disabled/>
        </el-form-item>
      </el-col>
      <el-col span="3">
        <el-form-item  label="姓名">
          <el-input  v-model="state.formData.customer.name" clearable disabled/>
        </el-form-item>
      </el-col>
        <el-col span="3">
        <el-form-item  label="客户电话号码">
          <el-input  placeholder="请输入电话号码" v-model="state.formData.customer.phone" clearable />
        </el-form-item>
      </el-col>
      <el-col span="3">
        <el-form-item  label="收获地址">
          <el-input  placeholder="请输入收货地" v-model="state.formData.line.endAddress" clearable />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  </div>

          <el-button @click="state.dialogFormVisible4Edit = false">取消</el-button>
          <el-button type="primary" @click="handleUpdate">
            确定
          </el-button>
        </span>
    </template>
  </el-dialog>




<!--  分页组件-->
    <div class="pagination-container">

      <el-pagination
          class="pagination"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :current-page="state.selectForm.currentPage"
          :page-size="state.selectForm.pageSize"
          :page-sizes="[5, 8, 11]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="state.selectForm.total">
      </el-pagination>
    </div>

</template>

<script setup>
import {provide, reactive, watch} from "vue";
import instance from "../../../request";
import { ElMessageBox, ElMessage } from 'element-plus';
import AddGoods from "@/pages/home/order/components/AddGoods.vue";
const state=reactive({
  name:'',
  dataList: [],//表格数据
  orderData:[],
  customerData:{},
  options: {
    drivers: [],
    driverList:[],
    customers:[],
    goods:[],
    depository:[],
    startAddress:[]
  },
  selectForm: {
    currentPage: 1,//当前页码
    pageSize:3,//每页显示的记录数
    total:0,//总记录数
   order:{
     customer: {
       name:''
     },
     line:{
       startAddress:''
     },
     createTime:'',
     orderStatus:''
   }
  },
  formData: {
  },
  addOrderForm:{
    id: '',
    customer: {
      name:''
    },
    line: {
      startAddress:'',
      endAddress:'',
    },
    drivers:[],
  },
  customerFormData:{},
  goodsFormData: {},
  dialogFormVisible: false,//添加表单是否可见
  dialogFormVisible4Edit:false,//编辑表单是否可见
  dialogFormVisibleDetail:false,//查看详细是否可见
  dialogFormVisibleAddGoods:false,//添加货物表单是否可见
  dialogFormVisibleCustomer:false,//添加客户表单是否可见
  rules: {//校验规则
    type: [{ required: true, message: '图书类别为必填项', trigger: 'blur' }],
    name: [{ required: true, message: '图书名称为必填项', trigger: 'blur' }]
  },

})

//多选选择器
const handleSizeChange = (newPageSize) => {
  state.selectForm.pageSize = newPageSize;
 load()
}
const handleCurrentChange = (newPageNumber) => {
  state.selectForm.currentPage = newPageNumber;
 load()
}

const sendOrder = (row) => {
  ElMessageBox.confirm('确定发货吗？', '确认发货', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
      .then(() => {
        // User confirmed, proceed with deletion
        instance.put("/order/send/" , row)
            .then((res) => {
              if (res.flag) {
                ElMessage.success(res.msg);
              } else {
                ElMessage.error(res.msg);
              }
            })
            .finally(() => {
              load();
            });
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消发货',
        })
      });
};
const endOrder = (row) => {
  ElMessageBox.confirm('确定收货吗？', '确认收货', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
      .then(() => {
        // User confirmed, proceed with deletion
        instance.put("/order/end/" , row)
            .then((res) => {
              if (res.flag) {
                ElMessage.success(res.msg);
              } else {
                ElMessage.error(res.msg);
              }
            })
            .finally(() => {
              load();
            });
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消收货',
        })
      });
};
const load=()=>{
  instance.post('/order/page',state.selectForm).then(res=>{
    state.selectForm.total=res.data.total
    console.log(res.data.list)
    if (res.data.list.length===0){

    }else {
      for (let i = 0; i < res.data.list.length; i++) {
        res.data.list[i].amount=res.data.list[i].amount.toFixed(2)
      }
    }
    state.dataList=res.data.list
  })
}


const addGoods=(row)=>{
  instance.get("/order/"+row.id).then(res=>{
    if(res.flag){
//展示弹层，加载数据
      state.orderData=res.data
      state.dialogFormVisibleAddGoods=true;
    }else{
      console.log("失败")
    }
  }).finally(()=>{
    load()
  })

  state.goodsFormData={}
}
const GoodTable=()=>{
  state.dataList.goodsList=state.goodsFormData

}
const handleDetail=(row)=>{
  instance.get("/order/"+row.id).then(res=>{
    state.orderData=res.data
    state.dialogFormVisibleDetail = true;
    console.log(state.orderData)
  })
}
const   handleCreate=()=> {
  getDepository()
  getCustomer()
  getStartAddress()
  // getDrivers()
  state.dialogFormVisible = true;
 state.selectForm= {
    currentPage: 1,//当前页码
        pageSize:3,//每页显示的记录数
        total:0,//总记录数
        order:{
      id : '',
          customer: {
        name:''
      },
      line:{
        startAddress:''
      },
      createTime:'',
          orderStatus:''
    }
  }
}

const resetForm=()=> {
  state.formData={};
}
const cancel=()=>{
  state.dialogFormVisible = false
  state.addOrderForm={
    id: '',
    customer: {
      name:''
    },
    line: {
      startAddress:'',
      endAddress:'',
    },
    drivers:[],
  }
  // this.$message.info("操作取消");
}
const openCustomer=()=>{
state.dialogFormVisibleCustomer=true;
  state.dialogFormVisible = false;
state.customerFormData={}
}

const addCustomer=()=>{
  instance.post("/customer/",state.customerFormData).then((res)=>{
//如果操作成功，关闭弹层，显示数据
    if(res.flag){
      state.dialogFormVisibleCustomer = false;
      console.log(res.msg);
      // state..success(res.msg);
    }else {
      // state..error(res.msg);
      console.log(res.msg);
    }

  }).finally(()=>{
handleCreate()
  })

}



//添加
const handleAdd=()=> {
  console.log(state.addOrderForm)
  instance.post("/order",state.addOrderForm).then((res)=>{
//如果操作成功，关闭弹层，显示数据
    if(res.flag){
      state.dialogFormVisible = false;
      // state.$message.success(res.msg);
    }else {
      // state.$message.error(res.msg);
    }
  }).finally(()=>{
    state.goodsList=[]

    state.addOrderForm={
      id: '',
          customer: {
        name:''
      },
      line: {
        startAddress:'',
            endAddress:'',
      },
      drivers:[],
    }
    load()
  });
}

const  handleEidt=(row)=> {

  console.log(row.id)
  instance.get("/order/"+row.id).then(res=>{
    if(res.flag){
//展示弹层，加载数据
      state.formData=res.data
      state.dialogFormVisible4Edit = true;
    }else{
      console.log("失败")
    }
  })
  // getDrivers()
}

const handleUpdate = () => {
  ElMessageBox.confirm('确定修改吗？', '确认修改', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
      .then(() => {
        // User confirmed, proceed with deletion
        instance.put("/order/" , state.formData)
            .then((res) => {
              if (res.flag) {
                ElMessage.success(res.msg);
              } else {
                ElMessage.error(res.msg);
              }
            })
            .finally(() => {
              load();
            });
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消修改',
        })
      });
};
const getDepository=()=>{
  state.options.depository=[]
  instance.get('/order/depository').then(res=>{
    console.log(res.data)
    state.options.depository=res.data
  })
}
const getStartAddress=()=>{
  state.options.startAddress=[]
  instance.get('/order/startAddress').then(res=>{
    console.log(res.data)
    state.options.startAddress=res.data
  })
}
const getCustomer=()=>{
  instance.get('/order/customer').then(res=>{
    console.log(res.data)
    state.options.customers=res.data
  })
}
const getGoods=()=>{
  // instance.get('/driver/').then(res=>{
  //   console.log(res.data)
  //   state.options=res.data
  // })
}


const handleDelete = (row) => {
  ElMessageBox.confirm('确定删除该订单吗？', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
      .then(() => {
        // User confirmed, proceed with deletion
        instance.delete("/order/" + row.id)
            .then((res) => {
              if (res.flag) {
                ElMessage.success(res.msg);
              } else {
                ElMessage.error(res.msg);
              }
            })
            .finally(() => {
              load();
            });
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      });
};

load()

provide('appState', state);



</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}

.filter-container .el-form-item {
  margin-right: 10px;
}

.filter-container .butT {
  margin-left: 10px;
}
</style>